import React, { PureComponent } from 'react';
import { Form, Row, Col, DatePicker, Input, Button, Modal, Tag, message } from 'antd';
import moment from 'moment';
import { getCookie } from '@/utils/utils';
import styles from './index.less';

import List from '@/pages/Staff';

const { TextArea } = Input;

export default class Index extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      selectedRows: [],
      newSelectedRows: [],
    };
  }

  onClose = record => {
    const { selectedRows = [] } = this.state;

    this.setState({
      selectedRows: selectedRows.filter(item => item.id !== record.id),
    });
  };

  okClick = () => {
    const { selectedRows = [] } = this.state;
    const { dispatch, form, modularName } = this.props;

    form.validateFields({ force: true }, (err, values) => {
      if (!err) {
        const { query = {}, ...extra } = values;
        const { phones, content, sendTime } = extra;
        let array = [];

        if (phones) {
          array = phones.split(',');
        }
        if (!((array && array.length > 0) || (selectedRows && selectedRows.length > 0))) {
          message.error('请添加要发送短信的电话', 1);
          return;
        }

        const list = [...array, ...selectedRows].map(item => {
          if (typeof item === 'string') {
            return {
              smsContent: content,
              smsPhone: item,
              smsSendTime: sendTime
                ? sendTime.format('YYYY-MM-DD HH:mm:ss')
                : moment().format('YYYY-MM-DD HH:mm:ss'),
              userDept: '长宁区城市运行值守保障管理系统',
              userName: getCookie('displayName'),
              userRealName: getCookie('displayName'),
            };
          } else if (typeof item === 'object') {
            return {
              smsContent: content,
              smsPhone: item.user_name,
              smsSendTime: sendTime
                ? sendTime.format('YYYY-MM-DD HH:mm:ss')
                : moment().format('YYYY-MM-DD HH:mm:ss'),
              userDept: '长宁区城市运行值守保障管理系统',
              userName: getCookie('displayName'),
              userRealName: getCookie('displayName'),
            };
          }
        });

        dispatch({
          type: `${modularName}/sendSms`,
          payload: {
            data: list,
            callback: () => {
              this.cancelClick();
            },
          },
        });
      }
    });
  };

  cancelClick = () => {
    const { dispatch, modularName } = this.props;

    dispatch({
      type: `${modularName}/changeState`,
      payload: { drawerVisible: false, editData: {} },
    });
  };

  render() {
    const { visible, selectedRows = [], newSelectedRows = [] } = this.state;
    const { form, event = {} } = this.props;
    const { getFieldDecorator } = form;

    return (
      <div>
        <Form layout="vertical">
          <Form.Item label={<span style={{ color: '#3f95ff' }}>手机号</span>}>
            {getFieldDecorator(
              'phones',
              {},
            )(<TextArea rows={6} placeholder="请输入手机号，多个用逗号隔开" />)}
          </Form.Item>
          <Form.Item
            label={
              <div>
                <div style={{ color: '#3f95ff', float: 'left' }}>通讯录</div>
                <div style={{ float: 'right' }}>
                  <Button
                    ghost
                    type="primary"
                    shape="round"
                    size="small"
                    style={{ marginRight: 8 }}
                    onClick={() => this.setState({ visible: true })}
                  >
                    选择
                  </Button>
                  <Button
                    ghost
                    type="danger"
                    shape="round"
                    size="small"
                    onClick={() => this.setState({ selectedRows: [] })}
                  >
                    清除
                  </Button>
                </div>
              </div>
            }
          >
            <div style={{ border: '1px solid #d9d9d9', borderRadius: 4, height: 136, padding: 10 }}>
              {selectedRows &&
                selectedRows.map(item => {
                  return (
                    <Tag
                      key={item.id}
                      closable
                      color="geekblue"
                      onClose={this.onClose.bind(this, item)}
                    >
                      {item.name}
                    </Tag>
                  );
                })}
            </div>
          </Form.Item>
          <Form.Item label="发送内容">
            {getFieldDecorator('content', {
              initialValue: event.eventBrief || undefined,
              rules: [{ required: true, message: '该项为必填项' }],
            })(<TextArea rows={6} placeholder="请输入发送内容" />)}
          </Form.Item>
          <Row gutter={16} type="flex">
            <Col span={12}>
              <Form.Item label="发送时间">
                {getFieldDecorator(
                  'sendTime',
                  {},
                )(
                  <DatePicker
                    showTime
                    placeholder="不填写则立即发送"
                    size="large"
                    style={{ width: '100%' }}
                  />,
                )}
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <Modal
          centered
          destroyOnClose
          maskClosable={false}
          title="选择人员"
          visible={visible}
          wrapClassName={styles.common_modal_wrapper}
          width={1024}
          onOk={() => this.setState({ visible: false, selectedRows: [...newSelectedRows] })}
          onCancel={() => this.setState({ visible: false, newSelectedRows: [] })}
        >
          <List
            currentUnit={{ id: -1 }}
            mode="select"
            queryMethod="addressBook"
            style={{ backgroundColor: '#fff' }}
            tableOptions={{
              scroll: { x: 975, y: 560, scrollToFirstRowOnChange: true },
              rowSelection: {
                onChange: (selectedRowKeys, rows) => {
                  this.setState({
                    newSelectedRows: [
                      ...newSelectedRows.filter(
                        item =>
                          selectedRowKeys.includes(item.id) &&
                          !rows.map(row => row.id).includes(item.id),
                      ),
                      ...rows,
                    ],
                  });
                },
              },
            }}
          />
        </Modal>
        <Button type="primary" size="large" style={{ marginRight: 16 }} onClick={this.okClick}>
          短信送报
        </Button>
        <Button size="large" onClick={this.cancelClick}>
          取消
        </Button>
      </div>
    );
  }
}
